package com.appology.buzz;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appology.oauth2.OAuth2ClientCredentials;
import com.appology.oauth2.PMF;
import com.google.api.client.extensions.appengine.auth.AbstractAppEngineFlowServlet;
import com.google.api.client.extensions.auth.helpers.Credential;
import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow;
import com.google.api.client.googleapis.extensions.auth.helpers.oauth2.draft10.GoogleOAuth2ThreeLeggedFlow;
import com.google.api.services.buzz.Buzz;
import com.google.api.services.buzz.Buzz.People;
import com.google.api.services.buzz.Buzz.People.Get;
import com.google.api.services.buzz.model.Activity;
import com.google.api.services.buzz.model.ActivityObject;
import com.google.api.services.buzz.model.ActivityObjectAttachments;
import com.google.api.services.buzz.model.ActivityObjectAttachmentsLinks;
import com.google.api.services.buzz.model.Person;

/*
* Class that will post the Chuck Norriss joke to Google Buzz.
*/
public class PostActivity extends AbstractAppEngineFlowServlet {

	private static final long serialVersionUID = 1L;
	private static final String ME = "@me"; // Default Google ID of current user logged into Google
	private static final String PARAMETER_JOKE = "joke";
	private static final String APPEND_URL = "\n(http://appology-chuck-norris.appspot.com)";
	private static final String CONTENT_TYPE = "text/plain";

	private static Buzz buzz;
	private static Activity result;

	@Override
	protected ThreeLeggedFlow newFlow(String userId) {

		return new GoogleOAuth2ThreeLeggedFlow(userId,
				OAuth2ClientCredentials.CLIENT_ID,
				OAuth2ClientCredentials.CLIENT_SECRET,
				OAuth2ClientCredentials.SCOPE,
				OAuth2ClientCredentials.CALLBACK_URL);
	}

	@Override
	protected void doGetWithCredentials(HttpServletRequest req,
			HttpServletResponse resp, Credential credential) throws IOException {

		// Set the content type as text/plain, and set the headers to explicitly
		// disallow caching in the browser. We always want a fresh copy of
		// whatever this page has to say
		resp.setContentType(CONTENT_TYPE);
		resp.setHeader("Expires", "Tue, 03 Jul 2001 06:00:00 GMT");
		resp.setHeader("Last-Modified", new Date().toString());
		resp.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
		resp.setHeader("Pragma", "no-cache");

		// Only procede if the "joke" paramter in the query string is not null
		// If it is null, then just output some text saying so.
		if (req.getParameter(PARAMETER_JOKE) != null) {

			// Instantiate a new Buzz object using the transport, and
			// jsonFactory provided by the superclass and the credential
			// obtained from the OAuth.
			buzz = new Buzz(getHttpTransport(), credential, getJsonFactory());

			// Instantiate a new Buzz Activity that we will post to the user's
			// stream
			Activity activity = new Activity();
			activity.buzzObject = new ActivityObject();
			// Add the joke, which was passed in as the "joke" parameter, as the
			// content of the Activity
			activity.buzzObject.content = req.getParameter(PARAMETER_JOKE)
					+ APPEND_URL;

			// Call execute() and send the Activity to Buzz.
			// Get it back as a new Activity
			result = buzz.activities.insert(ME, activity).execute();

			// If the activity is not empty, then we'll send back the profile
			// url of the user
			if (!result.isEmpty()) {
				resp.getWriter().println(
						buzz.people.get(ME).execute().profileUrl + "/buzz");
			} else {
				resp.getWriter().println("failed");
			}
		} else {
			resp.getWriter().println("No joke was submitted");
		}

	}

	@Override
	protected PersistenceManagerFactory getPersistenceManagerFactory() {
		return PMF.get();
	}

}
